package com.mck.utils;

import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.configurers.AuthorizeHttpRequestsConfigurer;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;

import java.util.Collections;

import java.util.ArrayList;
import java.util.List;

public class PermissionConfigBuilder {
    private final List<RequestMatcher> matchers = new ArrayList<>();
    private final List<String> authorities = new ArrayList<>();
    private boolean permitAll = false;
    private String currentPath; // 存储当前路径

    public static PermissionConfigBuilder path(String path) {
        return new PermissionConfigBuilder().addPath(path);
    }

    public PermissionConfigBuilder addPath(String path) {
        this.currentPath = path;
        matchers.add(new AntPathRequestMatcher(path));
        return this;
    }

    public PermissionConfigBuilder methods(HttpMethod... methods) {
        for (HttpMethod method : methods) {
            matchers.add(new AntPathRequestMatcher(currentPath, method.name()));
        }
        return this;
    }

    public PermissionConfigBuilder authorities(String... roles) {
        Collections.addAll(authorities, roles);
        return this;
    }

    public PermissionConfigBuilder permitAll() {
        this.permitAll = true;
        return this;
    }

    public void apply(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> {
            AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl config = auth.requestMatchers(matchers.toArray(new RequestMatcher[0]));

            if (permitAll) {
                config.permitAll();
            } else if (!authorities.isEmpty()) {
                config.hasAnyAuthority(authorities.toArray(new String[0]));
            } else {
                config.authenticated();
            }
        });
    }
}
